//
//  WXMPPTool.m
//  WeChat
//
//  Created by Yanting on 16/7/14.
//  Copyright © 2016年 Yanting. All rights reserved.
//

#import "WXMPPTool.h"
#import "XMPPFramework.h"
@interface WXMPPTool ()<XMPPStreamDelegate>
{
    XMPPStream *_xmppStream;
    XMPPResultBlock _resultBlock;
}

-(void)setupStream;

-(void)connectToHost;

-(void)sendPwdToHost;

-(void)sendOnline;

-(void)sendoffline;

-(void)disconnectFromHost;

@end
@implementation WXMPPTool

singleton_implementation(WXMPPTool)

#pragma mark -初始化XMPPStream
-(void)setupStream{
    //创建对象
    _xmppStream = [[XMPPStream alloc]init];
    //设置代理
    [_xmppStream addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
}
#pragma mark - 连接到服务器 传一个JID
-(void)connectToHost{
    if (_xmppStream == nil) {
        [self setupStream];
    }
    
    NSString *user = [WAccount shareAccount].user;
    XMPPJID *myJid = [XMPPJID jidWithUser:user domain:@"weiwu.local" resource:@"iphone"];
    _xmppStream.myJID = myJid;
    
    _xmppStream.hostName = @"127.0.0.1";
    
    _xmppStream.hostPort = 5222;
    
    NSError *error = nil;
    [_xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error];
    if (error) {
        NSLog(@"%@",error);
    }else{
        NSLog(@"connect success");
    }
}
#pragma mark - 连接成功 发送密码
-(void)sendPwdToHost{
    NSError *error = nil;
    NSString *password = [WAccount shareAccount].pwd;
    [_xmppStream authenticateWithPassword:password error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
}
#pragma mark - 发送一个”在线消息“给服务器
-(void)sendOnline{
    XMPPPresence *presence = [XMPPPresence presence];
    NSLog(@"%@",presence);
    [_xmppStream sendElement:presence];
}
#pragma mark - XMPPStream delegate
#pragma mark -连接成功
-(void)xmppStreamDidConnect:(XMPPStream *)sender{
    NSLog(@"%s",__func__);
    [self sendPwdToHost];
}
#pragma mark -登录成功
-(void)xmppStreamDidAuthenticate:(XMPPStream *)sender{
    NSLog(@"%s",__func__);
    if (_resultBlock) {
        _resultBlock(XMPPResultTypeLoginSuccess);
        //回调后立马清空 防止循环引用
        _resultBlock = nil;
    }
    [self sendOnline];
}
#pragma mark -登录失败
-(void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error{
    if (_resultBlock) {
        _resultBlock(XMPPResultTypeLoginFailure);
    }
    NSLog(@"%s--%@",__func__,error);
}
#pragma mark - 用户登录（公用方法）
-(void)xmppLogin:(XMPPResultBlock)resultBlock{
    
    [_xmppStream disconnect];
    
    _resultBlock = resultBlock;
    
    [self connectToHost];
}
#pragma mark - 用户注销
-(void)xmpplogout{
    //发送离线消息
    [self sendoffline];
    
    //断开与服务器连接
    [self disconnectFromHost];
}
#pragma mark - 发送一个”离线线消息“给服务器
-(void)sendoffline{
    XMPPPresence *offline = [XMPPPresence presenceWithType:@"unavailable"];
    
    [_xmppStream sendElement:offline];
}

-(void)disconnectFromHost{
    [_xmppStream disconnect];
}
@end
